//
//  QLMServiceManDetailVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/14.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMServiceManDetailVC.h"

#import "QLMServiceTopTabCell.h"
#import "QLMServiceMidTabCell.h"
#import "QLMServiceBotTabCell.h"

#import "QLMSerRouteMapVC.h"

@interface QLMServiceManDetailVC ()<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate,BMKRouteSearchDelegate,BMKMapViewDelegate,BMKGeoCodeSearchDelegate>{
    
    BMKMapView *_mapView;
    NSArray *tipsArray;
    BMKRouteSearch *_routeSearch;
    BMKGeoCodeSearch *_geocodesearch;
    
    NSString *distanceStr;
    NSString *timeStr;
    
    NSDictionary *geoEndDic;
    NSTimer *timer;
    
    // 在地图上绘制的折线
    BMKPolyline *routeLine;
    NSMutableDictionary *astartdic;
    
    BOOL arriveBool;
    NSArray *alocationArray;
    QLMServiceMidTabCell *middleCell;
}
@property (nonatomic,strong) UITableView *sertableview;
@end

@implementation QLMServiceManDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"服务工程师详情";

    astartdic=[NSMutableDictionary dictionary];
    geoEndDic=[NSDictionary dictionary];
    _routeSearch = [[BMKRouteSearch alloc] init];
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    
    if ([_orderStatus isEqualToString:@"3"]) {
        timer = [NSTimer scheduledTimerWithTimeInterval:120 target:self selector:@selector(requestLocationData) userInfo:nil repeats:YES];
    }
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton setImage:[UIImage imageNamed:@"call"] forState:UIControlStateNormal];
    [rightButton setBackgroundColor:[UIColor clearColor]];
    rightButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
    [rightButton addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                   target:nil
                                   action:nil];
    fixedSpace.width = 0;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:rightItem,fixedSpace,nil];

    
    tipsArray=[NSArray arrayWithObjects:@"服务工程师信息",@"店铺信息",@"实时信息", nil];
    
    CGRect rect = CGRectMake(0, 0, kScreen_width, kScreen_height-QLM_StatusBarAndNavigationBarHeight-IOS11_OR_LATER_SPACE(34));
    _sertableview=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    _sertableview.backgroundColor=[UIColor clearColor];
    _sertableview.delegate=self;
    _sertableview.dataSource=self;
    _sertableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    _sertableview.showsVerticalScrollIndicator=NO;
    _sertableview.showsHorizontalScrollIndicator=NO;
    _sertableview.tableFooterView=[UIView new];
    [self.view addSubview:_sertableview];
    
    _sertableview.bounces=NO;

    if (@available(iOS 11.0, *)) {
        _sertableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    
    if (!_isScanInfoBool) {
        _routeSearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
        _geocodesearch.delegate = self;
        geoEndDic=[NSDictionary dictionaryWithObjectsAndKeys:_repairLatitude,@"latitu",_repairLongitude,@"longtitu", nil];
        [self requestLocationData];
        
        [timer setFireDate:[NSDate date]];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    _routeSearch.delegate = nil; // 不用时，置nil
    _geocodesearch.delegate = nil;
    _mapView.delegate=nil;
}

- (void)leftClick{
    [self.view endEditing:YES];
    
    [timer invalidate];
    timer = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [self clearMapView];
    
    [timer invalidate];
    timer = nil;
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"Astartdic"];
    if ([dic allKeys]!=0) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Astartdic"];
    }
}

- (void)clearMapView{
    if (_routeSearch != nil) {
        _routeSearch = nil;
    }
    if (_geocodesearch != nil) {
        _geocodesearch = nil;
    }
    if (_mapView) {
        _mapView = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)requestLocationData{
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:_erpOrderId forKey:@"erpOrderId"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/test/repairOrder/serverTrace" withParamers:paramerDic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            alocationArray=[NSArray arrayWithArray:responseObject[@"data"]];
                            if ([_orderStatus isEqualToString:@"3"]) {
                                
                                if (alocationArray.count==1) {
                                    double latitude=[[alocationArray[0] objectForKey:@"latitude"] doubleValue];
                                    double longtitude=[[alocationArray[0] objectForKey:@"longitude"] doubleValue];
                                    [astartdic setObject:@(latitude) forKey:@"lat"];
                                    [astartdic setObject:@(longtitude) forKey:@"long"];
                                    [[NSUserDefaults standardUserDefaults] setObject:astartdic forKey:@"Astartdic"];
                                }
                                
                                NSDictionary *serDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"Astartdic"];
                                [self _startSearchRouteLine:serDic endDic:geoEndDic];
                            }else{
                                if (alocationArray.count>1) {
                                    arriveBool=YES;
                                    NSMutableDictionary *tmpStartDic=[self resultDic:alocationArray atIndex:0];
                                    NSMutableDictionary *tmpEndDic=[self resultEndDic:alocationArray atIndex:alocationArray.count-1];
                                    [self _startSearchRouteLine:tmpStartDic endDic:tmpEndDic];
                                    [self configureRoutes:alocationArray];
                                }
                            }
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (NSMutableDictionary *)resultDic:(NSArray *)locationArr atIndex:(NSInteger)row{
    NSMutableDictionary *tmpDic=[NSMutableDictionary dictionary];
    CLLocationDegrees latitude=[[locationArr[row] objectForKey:@"latitude"] doubleValue];
    CLLocationDegrees longitude=[[locationArr[row] objectForKey:@"longitude"] doubleValue];
    [tmpDic setObject:@(latitude) forKey:@"lat"];
    [tmpDic setObject:@(longitude) forKey:@"long"];
    return tmpDic;
}

- (NSMutableDictionary *)resultEndDic:(NSArray *)locationArr atIndex:(NSInteger)row{
    NSMutableDictionary *tmpDic=[NSMutableDictionary dictionary];
    CLLocationDegrees latitude=[[locationArr[row] objectForKey:@"latitude"] doubleValue];
    CLLocationDegrees longitude=[[locationArr[row] objectForKey:@"longitude"] doubleValue];
    [tmpDic setObject:@(latitude) forKey:@"latitu"];
    [tmpDic setObject:@(longitude) forKey:@"longtitu"];
    return tmpDic;
}

- (void)_startGeoCodeSearchData{
    BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
    geocodeSearchOption.city=[NSString stringWithFormat:@"%@",@""];
    geocodeSearchOption.address = [NSString stringWithFormat:@"%@",_addressDetail];
    BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
    if(flag){
        NSLog(@"geo检索发送成功");
    }else{
        NSLog(@"geo检索发送失败");
    }
}

#pragma mark - Action
- (void)addAnnotation:(UILongPressGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        [self clearMapView];
        [timer setFireDate:[NSDate distantFuture]];
        
        QLMSerRouteMapVC *routeVC=[QLMSerRouteMapVC new];
        if (arriveBool) {
            routeVC.arriveBool=YES;
            routeVC.locationArray=alocationArray;
        }else{
            routeVC.astartdic=astartdic;
            routeVC.geoEndDic=geoEndDic;
        }
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:routeVC animated:YES];
    }
}

- (void)rightClick{
    __weak QLMServiceManDetailVC *weakself = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [self addActionTarget:alert title:@"联系服务工程师" color:UIColorFromRGB(0xff3b30) action:^(UIAlertAction *action) {
        [weakself callPhoneNumber];
    }];
    [self addActionTarget:alert title:@"联系客服人员" color:UIColorFromRGB(0x157efb) action:^(UIAlertAction *action) {
        [weakself callSerPhoneNumber];
    }];
    [self addCancelActionTarget:alert title:@"取消"];
    [self presentViewController:alert animated:YES completion:nil];
}

//拨打服务工程师电话
- (void)callPhoneNumber{
    
    NSString *phone=_serDetailModel.servicerTelNo;
    if (!_isScanInfoBool) {
        phone=_orderSerManModel.servicerTelNo;
    }
    NSString *telNumberStr = [NSString stringWithFormat:@"tel://%@",phone];
    
    UIWebView *webView =[[UIWebView alloc] initWithFrame:CGRectZero];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:telNumberStr]]];
    [self.view addSubview:webView];
}

//拨打客服人员电话
- (void)callSerPhoneNumber{
    
    NSString *telNumberStr = [NSString stringWithFormat:@"tel://%@",@"4008896977"];
    UIWebView *webView =[[UIWebView alloc] initWithFrame:CGRectZero];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:telNumberStr]]];
    [self.view addSubview:webView];
}

#pragma mark - UIActionSheet delegate
-(void)addCancelActionTarget:(UIAlertController*)alertController title:(NSString *)title{
    UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    
    if (IOS9_OR_LATER) {
        [action setValue:UIColorFromRGB(0x157efb) forKey:@"_titleTextColor"];
    }
    [alertController addAction:action];
}

- (void)addActionTarget:(UIAlertController *)alertController title:(NSString *)title color:(UIColor *)color action:(void(^)(UIAlertAction *action))actionTarget{
    UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        actionTarget(action);
    }];
    if (IOS9_OR_LATER) {
        [action setValue:color forKey:@"_titleTextColor"];
    }
    [alertController addAction:action];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UITableView datasource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==3) {
        return 0.1;
    }
    return 34;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView=[[UIView alloc] init];
    headerView.backgroundColor=[UIColor whiteColor];
    if (section!=3) {
        UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
        newButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        newButton.frame = CGRectMake(10, 5, 160, 24);
        [newButton setImage:[UIImage imageNamed:@"icon"] forState:UIControlStateNormal];
        [newButton setTitle:tipsArray[section] forState:UIControlStateNormal];
        [newButton setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
        newButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
        newButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        newButton.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        [headerView addSubview:newButton];
    }

    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==2||section==3) {
        return 0.1;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView=[[UIView alloc] init];
    footerView.backgroundColor=[UIColor clearColor];
    return footerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (_isScanInfoBool) {
        return 2;
    }
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return 140;
    }else if (indexPath.section==1) {
         return [middleCell autoChangeHeightWithLabel:middleCell.storeAddressLabel]+30+10;
    }else if (indexPath.section==2) {
        return 60;
    }
    return 300;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        QLMServiceTopTabCell *cell=[QLMServiceTopTabCell cellWithTableView:tableView];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        NSString *iconPath=_serDetailModel.iconPath;
        NSString *servicerUserName=_serDetailModel.servicerUserName;
        NSString *servicerLevelNum=_serDetailModel.servicerLevelNum;
        NSString *customerEvaluationNumber=_serDetailModel.customerEvaluationNumber;
        if (!_isScanInfoBool) {
            iconPath=_orderSerManModel.iconPath;
            servicerUserName=_orderSerManModel.servicerUserName;
            servicerLevelNum=_orderSerManModel.servicerLevelNum;
            customerEvaluationNumber=_customerEvaluationNumber;
        }
        
        NSString *picStr=[NSString stringWithFormat:@"%@%@",kBaseImageUrl,iconPath];
        [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:picStr] placeholderImage:[UIImage imageNamed:@"header"]];
        
        cell.nameLabel.text=servicerUserName;
        
        CWStarRateView *starRateView1 = [[CWStarRateView alloc] initWithFrame:CGRectMake(cell.nameLabel.frame.origin.x,87.5,80,15) numberOfStars:5];
        starRateView1.scorePercent = [servicerLevelNum integerValue]/5.0;
        starRateView1.allowIncompleteStar = NO;
        starRateView1.hasAnimation = NO;
        starRateView1.userInteractionEnabled=NO;
        starRateView1.backgroundColor=[UIColor clearColor];
        [cell addSubview:starRateView1];
        
        CWStarRateView *starRateView2 = [[CWStarRateView alloc] initWithFrame:CGRectMake(cell.nameLabel.frame.origin.x,112.5,80,15) numberOfStars:5];
        starRateView2.scorePercent = [customerEvaluationNumber integerValue]/5.0;
        starRateView2.allowIncompleteStar = YES;
        starRateView2.hasAnimation = NO;
        starRateView2.userInteractionEnabled=NO;
        starRateView2.backgroundColor=[UIColor clearColor];
        [cell addSubview:starRateView2];
        
        return cell;
    }else if(indexPath.section==1){
        middleCell=[QLMServiceMidTabCell cellWithTableView:tableView];
        NSString *companyName=_serDetailModel.deptName;
        NSString *address=_serDetailModel.address;
        if (!_isScanInfoBool) {
            companyName=_orderSerManModel.deptName;
            address=_orderSerManModel.address;
        }
        
        middleCell.storeNameLabel.text=companyName;
        middleCell.storeAddressLabel.text=address;
        
        middleCell.selectionStyle=UITableViewCellSelectionStyleNone;
        return middleCell;
    }else if (indexPath.section==2){
        QLMServiceBotTabCell *cell=[QLMServiceBotTabCell cellWithTableView:tableView];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.userInteractionEnabled=YES;
        
        cell.distanceLabel.text=distanceStr;
        cell.timeLabel.text=timeStr;
    
        return cell;
    }
    
    static NSString *cellid=@"BMKMapViewCellId";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];
    if (!cell) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        if (_mapView==nil) {
            _mapView=[[BMKMapView alloc] initWithFrame:CGRectMake(0,0,kScreen_width,300)];
            _mapView.mapType=BMKMapTypeStandard;
            _mapView.delegate=self;
        }

        UIButton *fullScreenBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        fullScreenBtn.frame=CGRectMake(kScreen_width-20-10, 10, 16, 16);
        [fullScreenBtn setImage:[UIImage imageNamed:@"fullscreen"] forState:UIControlStateNormal];
        [fullScreenBtn addTarget:self action:@selector(addAnnotation:) forControlEvents:UIControlEventTouchUpInside];
        [_mapView addSubview:fullScreenBtn];
        
        [cell addSubview:_mapView];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    _sertableview.scrollEnabled=YES;
}

#pragma mark - BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    _sertableview.scrollEnabled=NO;
}

- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation{
   
    if ([annotation isKindOfClass:[RouteAnnotation class]]) {
        return [(RouteAnnotation*)annotation getRouteAnnotationView:view];
    }else{
        // 生成重用标示identifier
        NSString *AnnotationViewID = @"xidanMark";
        // 检查是否有重用的缓存
        BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        // 缓存没有命中，自己构造一个，一般首次添加annotation代码会运行到此处
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorGreen;
            // 设置重天上掉下的效果(annotation)
            ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
        }
        // 设置位置
        annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
        annotationView.annotation = annotation;
        // 单击弹出泡泡，弹出泡泡前提annotation必须实现title属性
        annotationView.canShowCallout = YES;
        // 设置是否可以拖拽
        annotationView.draggable = NO;
        return annotationView;
    }
    
    return nil;
}

- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay{
    
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor alloc] initWithRed:0 green:1 blue:1 alpha:1];
        polylineView.strokeColor = [UIColor greenColor];
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    return nil;
}

#pragma mark - BMKPlanNode init
- (BMKPlanNode *)SetUpStartPlanNode:(NSDictionary *)dic{
    BMKPlanNode *start = [[BMKPlanNode alloc]init];
    start.pt = (CLLocationCoordinate2D){[dic[@"latitu"] doubleValue], [dic[@"longtitu"] doubleValue]};
    return start;
}

#pragma mark - BMKMapview delegate
- (void)_startSearchRouteLine:(NSDictionary *)tmpStartDic endDic:(NSDictionary *)tmpEndDic{
    
    NSDictionary *startdic=[NSDictionary dictionaryWithObjectsAndKeys:tmpStartDic[@"lat"],@"latitu",tmpStartDic[@"long"],@"longtitu", nil];
    
//    NSDictionary *startdic=[NSDictionary dictionaryWithObjectsAndKeys:@"30.688368",@"latitu",@"113.990005",@"longtitu", nil];
    
    BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init];
    drivingRouteSearchOption.from = [self SetUpStartPlanNode:startdic];
    drivingRouteSearchOption.to = [self SetUpStartPlanNode:tmpEndDic];
    
    drivingRouteSearchOption.drivingRequestTrafficType = BMK_DRIVING_REQUEST_TRAFFICE_TYPE_NONE;//不获取路况信息
    BOOL flag = [_routeSearch drivingSearch:drivingRouteSearchOption];
    if(flag){
        NSLog(@"car检索发送成功");
    }else{
        NSLog(@"car检索发送失败");
    }
}

- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        geoEndDic=[NSDictionary dictionaryWithObjectsAndKeys:@(result.location.latitude),@"latitu",@(result.location.longitude),@"longtitu", nil];
//        NSLog(@"result.location.longitude = %f  %f",result.location.latitude,result.location.longitude);
        [self requestLocationData];
    }else{
        ETToast(@"地址有误！");
    }
}

- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error {
    
    if (error == BMK_SEARCH_NO_ERROR) {
        
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        if (!arriveBool) {
            // 计算路线方案中的路段数目
            NSInteger size = [plan.steps count];
            int planPointCounts = 0;
            for (int i = 0; i < size; i++) {
                
                BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
                if(i==0){
                    RouteAnnotation* item = [[RouteAnnotation alloc]init];
                    item.coordinate = plan.starting.location;
                    item.title = @"起点";
                    item.type = 0;
                    [_mapView addAnnotation:item]; // 添加起点标注
                    
                }
                if(i==size-1){
                    RouteAnnotation* item = [[RouteAnnotation alloc]init];
                    item.coordinate = plan.terminal.location;
                    item.title = @"终点";
                    item.type = 1;
                    [_mapView addAnnotation:item]; // 添加起点标注
                }
                //添加annotation节点
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = transitStep.entrace.location;
                item.title = transitStep.entraceInstruction;
                item.degree = transitStep.direction * 30;
                item.type = 4;
                [_mapView addAnnotation:item];
                //轨迹点总数累计
                planPointCounts += transitStep.pointsCount;
            }
            // 添加途经点
            if (plan.wayPoints) {
                for (BMKPlanNode* tempNode in plan.wayPoints) {
                    RouteAnnotation* item = [[RouteAnnotation alloc]init];
//                    item = [[RouteAnnotation alloc]init];
                    item.coordinate = tempNode.pt;
                    item.type = 5;
                    item.title = tempNode.name;
                    [_mapView addAnnotation:item];
                }
            }
            //轨迹点
            BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
            int i = 0;
            for (int j = 0; j < size; j++) {
                BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
                int k=0;
                for(k=0;k<transitStep.pointsCount;k++) {
                    temppoints[i].x = transitStep.points[k].x;
                    temppoints[i].y = transitStep.points[k].y;
                    i++;
                }
            }
            // 通过points构建BMKPolyline
            BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
            [_mapView addOverlay:polyLine]; // 添加路线overlay
            delete []temppoints;
            [self mapViewFitPolyLine:polyLine];
        }
        
        distanceStr=[NSString stringWithFormat:@"%.3fKm",plan.distance/1000.0];
        timeStr=[NSString stringWithFormat:@"%d小时%d分钟%d秒",plan.duration.hours,plan.duration.minutes,plan.duration.seconds];
        
        [_sertableview reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

//根据polyline设置地图范围
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine {
    CGFloat leftTopX, leftTopY, rightBottomX, rightBottomY;
    if (polyLine.pointCount < 1) {
        return;
    }
    BMKMapPoint pt = polyLine.points[0];
    // 左上角顶点
    leftTopX = pt.x;
    leftTopY = pt.y;
    // 右下角顶点
    rightBottomX = pt.x;
    rightBottomY = pt.y;
    for (int i = 1; i < polyLine.pointCount; i++) {
        BMKMapPoint pt = polyLine.points[i];
        leftTopX = pt.x < leftTopX ? pt.x : leftTopX;
        leftTopY = pt.y < leftTopY ? pt.y : leftTopY;
        rightBottomX = pt.x > rightBottomX ? pt.x : rightBottomX;
        rightBottomY = pt.y > rightBottomY ? pt.y : rightBottomY;
    }
    BMKMapRect rect;
    rect.origin = BMKMapPointMake(leftTopX, leftTopY);
    rect.size = BMKMapSizeMake(rightBottomX - leftTopX, rightBottomY - leftTopY);
    UIEdgeInsets padding = UIEdgeInsetsMake(30, 0, 100, 0);
    BMKMapRect fitRect = [_mapView mapRectThatFits:rect edgePadding:padding];
    [_mapView setVisibleMapRect:fitRect];
}

#pragma mark - 绘制轨迹
- (void)configureRoutes:(NSArray *)locationPoint{
    // 1、分配内存空间给存储经过点的数组
    BMKMapPoint *pointArray = (BMKMapPoint *)malloc(sizeof(CLLocationCoordinate2D) * locationPoint.count);
    // 2、创建坐标点并添加到数组中
    NSInteger idxCount=locationPoint.count;
    if (locationPoint.count>300) {
        idxCount=300;
    }
    
    NSInteger size = idxCount;
    for (int i = 0; i < size; i++) {
        
        CLLocationDegrees latitude=[[locationPoint[i] objectForKey:@"latitude"] doubleValue];
        CLLocationDegrees longitude=[[locationPoint[i] objectForKey:@"longitude"] doubleValue];
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude);
        
        BMKMapPoint point = BMKMapPointForCoordinate(coordinate);
        if (i==0) {
            _mapView.centerCoordinate = coordinate;
        }
        pointArray[i] = point;
        
        if(i==0){
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = coordinate;
            item.title = @"起点";
            item.type = 0;
            [_mapView addAnnotation:item]; // 添加起点标注
        }
        
        if(i==size-1){
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = coordinate;
            item.title = @"终点";
            item.type = 1;
            [_mapView addAnnotation:item]; // 添加起点标注
        }
        
        //添加annotation节点
        RouteAnnotation* item = [[RouteAnnotation alloc]init];
        item.coordinate = coordinate;
        item.title = @"";
//        item.degree = transitStep.direction * 30;
        item.type = 4;
        [_mapView addAnnotation:item];
        
//        RouteAnnotation* tmpItem = [[RouteAnnotation alloc]init];
//        tmpItem.coordinate = coordinate;
//        tmpItem.type = 5;
//        tmpItem.title = @"";
//        [_mapView addAnnotation:item];
    }
    // 3、防止重复绘制
    if (routeLine) {
        //在地图上移除已有的坐标点
        [_mapView removeOverlay:routeLine];
    }
    // 4、画线
    routeLine = [BMKPolyline polylineWithPoints:pointArray count:locationPoint.count];
    // 5、将折线(覆盖)添加到地图
    if (nil != routeLine) {
        [_mapView addOverlay:routeLine];
    }
    [self mapViewFitPolyLine:routeLine];
    free(pointArray);
}

@end
